package com.huawei.cloud.phone.management.infrastructure.db.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DataSourceConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    public DruidDataSource getDruidDataSource() {
        return new DruidDataSource();
    }

    @Bean(value = "masterDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource getMasterDataSource(@Autowired DruidDataSource dataSource) {
        return dataSource.cloneDruidDataSource();
    }

    @Bean(value = "slave1DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.slave1")
    public DataSource getSlave1DataSource(@Autowired DruidDataSource dataSource) {
        return dataSource.cloneDruidDataSource();
    }

    @Bean(value = "slave2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.slave2")
    public DataSource getSlave2DataSource(@Autowired DruidDataSource dataSource) {
        return dataSource.cloneDruidDataSource();
    }

    @Bean(value = "dataSource")
    public DataSource getDataSource(@Qualifier("masterDataSource") DataSource masterDataSource,
                                    @Qualifier("slave1DataSource") DataSource slave1DataSource,
                                    @Qualifier("slave2DataSource") DataSource slave2DataSource) {
        Map<Object, Object> allDataSource = new HashMap<>();
        allDataSource.put(DataSourceName.MASTER, masterDataSource);
        allDataSource.put(DataSourceName.SLAVE1, slave1DataSource);
        allDataSource.put(DataSourceName.SLAVE2, slave2DataSource);
        return new DynamicDataSource(masterDataSource, allDataSource);
    }

    @Bean
    public PlatformTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
